package com.server.questionbank.snframe.controller.Course;

import com.server.questionbank.snframe.controller.Course.pojo.CreateCourse;
import com.server.questionbank.snframe.controller.Course.pojo.JoinCourse;
import com.server.questionbank.snframe.domain.Course.CourseComment;
import com.server.questionbank.snframe.domain.Course.Member.CusStudyGroup;
import com.server.questionbank.snframe.domain.Course.Type.CourseDifficulty;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.domain.Course.TCourse;
import com.server.questionbank.snframe.domain.TCollection;
import com.server.questionbank.snframe.domain.User.TUser;
import com.server.questionbank.snframe.mapper.Course.Resource.CourseFilesMapper;
import com.server.questionbank.snframe.service.CourseService.CourseCommentService;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberGroupService;
import com.server.questionbank.snframe.service.CourseService.Member.CusMemberService;
import com.server.questionbank.snframe.service.CourseService.TCourseService;
import com.server.questionbank.snframe.service.TCollectionService;
import com.server.questionbank.snframe.service.UsersService.UsersService;
import com.server.questionbank.snframe.util.AvatarProcessing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 课程控制类
 */
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private TCourseService tCourseService;

    @Autowired
    private CourseFilesMapper courseFilesMapper;

    @Autowired
    private CusMemberGroupService cusMemberGroupService;

    @Autowired
    private CusMemberService cusMemberService;

    @Autowired
    private TCollectionService tCollectionService;

    @Autowired
    private CourseCommentService courseCommentService;

    @Autowired
    UsersService usersService;

    // 创建课程
    @PostMapping("/create")
    public ResponseResult<List<CourseDifficulty>> create(@RequestBody CreateCourse newCourse) {
        // 处理封面
        String avatar = null;
        try
        {
            avatar = AvatarProcessing.AvatarProcessing(newCourse.getCoverData(), 300, 150);
        } catch (Exception e){ return ResponseResult.error("封面处理失败!"); }
        if (avatar == null) return ResponseResult.error("封面处理失败!");

        TUser user = usersService.getLoginUser();
        TCourse tCourse = new TCourse();
        tCourse.setCourseName(newCourse.getCourseName());
        tCourse.setCourseDifficultyId(newCourse.getCourseDifficultyId());
        tCourse.setCourseDescription(newCourse.getCourseDescription());
        tCourse.setCreateBy(user.getUserId());

        if(tCourse.getCourseName().isEmpty()) return ResponseResult.error("课程名称不能为空!");

        try {
            if (tCourseService.createCourse(tCourse, avatar, newCourse.getCourseType(), newCourse.getCourseLabel()))
            {
                return ResponseResult.success();
            } else return ResponseResult.error("创建课程失败!");
        } catch (Exception e) { e.printStackTrace(); return ResponseResult.error("创建课程失败!"); }
    }

    // 加入课程
    @PostMapping("/joinCourse")
    public ResponseResult<Integer> joinCourse(@RequestBody JoinCourse joinCourseData)
    {
        // 获取用户信息
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("请先登录!");
        // 判断是否是课程成员
        Integer permission = cusMemberService.getMemberPermission(joinCourseData.getCourseId(), user.getUserId()).getPermissionFlags();
        if (permission > 0) return ResponseResult.success("您已经是课程成员!",0);
        try {
            // 加入课程
            Integer result = cusMemberService.joinCourse(
                    joinCourseData.getCourseId(),
                    user.getUserId(), joinCourseData.getUserNickName());
            if (result >= 1)
                return ResponseResult.success("加入课程成功！", 1);
        } catch (Exception e)
        {
            return ResponseResult.error("加入课程失败!");
        }
        return ResponseResult.error("加入课程失败!");
    }

    // 收藏课程
    @PostMapping("/collectCourse")
    public ResponseResult<Integer> collectCourse(@RequestBody Map<String, Long> map)
    {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("请先登录!");
        // 获取收藏课程
        TCollection collection = tCollectionService.selectCollection(user.getUserId(), map.get("courseId"), "course");
        if (collection != null) return ResponseResult.success("您已收藏此课程!", 0);
        try {
            Integer result = tCollectionService.insertCollection(user.getUserId(), map.get("courseId"), "course");
            if (result >= 1)
                return ResponseResult.success("收藏课程成功！", 1);
        } catch (Exception e)
        {
            e.printStackTrace();
            return ResponseResult.error("收藏课程失败!");
        }
        return ResponseResult.error("收藏课程失败!");
    }

    // 取消收藏课程
    @PostMapping("/cancelCollectCourse")
    public ResponseResult<Integer> cancelCollectCourse(@RequestBody Map<String, Long> map)
    {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("请先登录!");
        // 获取收藏课程
        TCollection collection = tCollectionService.selectCollection(user.getUserId(), map.get("courseId"), "course");
        if (collection == null) return ResponseResult.success("您未收藏此课程!", 0);
        try {
            Integer result = tCollectionService.deleteCollection(collection.getCollectionId());
            if (result >= 1)
                return ResponseResult.success("取消收藏课程成功！", 1);
        } catch (Exception e)
        {
            return ResponseResult.error("取消收藏课程失败!");
        }
        return ResponseResult.error("取消收藏课程失败!");
    }

    // 获取成员权限
    @PostMapping("/getMemberPermission")
    public ResponseResult<Integer> getMemberPermission(@RequestBody Map<String, Long> map)
    {
        Long courseId = map.get("courseId");
        Long memberId = map.get("memberId");
        if (courseId == null) return ResponseResult.error("参数错误!");
        if (memberId == null) return ResponseResult.success(0);
        Integer permission = cusMemberService.getMemberPermission(courseId, memberId).getPermissionFlags();
        return ResponseResult.success(permission);
    }

    // 获取课程班级列表
    @PostMapping("/getClassList")
    public ResponseResult<List<CusStudyGroup>> getClassList(@RequestBody Map<String, Long> map)
    {
        Long courseId = map.get("courseId");
        if (courseId == null) return ResponseResult.error("参数错误!");
        List<CusStudyGroup> classList = cusMemberGroupService.getCusStudyGroupByCourseId(courseId);
        for (CusStudyGroup group : classList) group.setUserRegistCus(cusMemberService.getAllMember(courseId, group.getGroupId()));
        return ResponseResult.success(classList);
    }

    // 评论课程
    @PostMapping("/commentCourse")
    public ResponseResult<Integer> commentCourse(@RequestBody CourseComment courseComment)
    {
        if (courseComment == null) return ResponseResult.error("参数错误!");
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("请先登录!");
        courseComment.setUserId(user.getUserId());
        Integer permission = cusMemberService.getMemberPermission(courseComment.getCourseId(), user.getUserId()).getPermissionFlags();
        if (permission <= 0) return ResponseResult.error("您不是课程成员，无法评论!");
        if (courseCommentService.insertCourseComment(courseComment))
            return ResponseResult.success(1);
        return ResponseResult.error("评论失败!");
    }

    // 删除评论
    @PostMapping("/deleteComment")
    public ResponseResult<Integer> deleteComment(@RequestBody Map<String, Long> map)
    {
        TUser user = usersService.getLoginUser();
        if (user == null) return ResponseResult.error("请先登录!");
        Long commentId = map.get("commentId");
        if (commentId == null) return ResponseResult.error("参数错误!");
        CourseComment courseComment = courseCommentService.selectCourseCommentById(commentId);
        if (courseComment == null) return ResponseResult.error("评论不存在!");
        if (!courseComment.getUserId().equals(user.getUserId())) return ResponseResult.error("没有权限!");
        if (courseCommentService.deleteCourseComment(commentId))
            return ResponseResult.success(1);
        return ResponseResult.error("删除失败!");
    }

}
